﻿using phhui;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace CoinBill
{
    public partial class Form1 : Form
    {
        private delegate void dltxt();
        private System.Timers.Timer t;
        private XmlHelper xml;
        private Dictionary<string, double> priceList = new Dictionary<string, double>();
        public Form1()
        {
            InitializeComponent();
        }
        private void tb_num_TextChanged(object sender, EventArgs e)
        {
            if (tb_num.Text.Trim().Equals("数量")) tb_num.ForeColor = Color.DarkGray;
            else tb_num.ForeColor = Color.Black;
        }

        private void tb_price_TextChanged(object sender, EventArgs e)
        {
            if (tb_price.Text.Trim().Equals("单价"))tb_price.ForeColor = Color.DarkGray;
            else tb_price.ForeColor = Color.Black;
        }

        private void tb_price_Enter(object sender, EventArgs e)
        {
            if (tb_price.Text.Trim().Equals("单价")) tb_price.Text = "";
        }

        private void tb_price_Leave(object sender, EventArgs e)
        {
            if (tb_price.Text.Trim().Length<1) tb_price.Text = "单价";
            if (tb_price.Text.Trim().Equals("单价")) tb_price.ForeColor = Color.DarkGray;
            else tb_price.ForeColor = Color.Black;
        }

        private void tb_num_Enter(object sender, EventArgs e)
        {
            if (tb_num.Text.Trim().Equals("数量")) tb_num.Text = "";
        }

        private void tb_num_Leave(object sender, EventArgs e)
        {
            if (tb_num.Text.Trim().Length < 1) tb_num.Text = "数量";
            if (tb_num.Text.Trim().Equals("数量")) tb_num.ForeColor = Color.DarkGray;
            else tb_num.ForeColor = Color.Black;
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (cb_list.Text.Trim().Equals("选择币种"))
            {
                MessageBox.Show("请选择币种");
                return;
            }
            if (tb_num.Text.Trim().Length < 1)
            {
                MessageBox.Show("请输入单价");
                return;
            }
            if (tb_price.Text.Trim().Length < 1)
            {
                MessageBox.Show("请输入数量");
                return;
            }
            Hashtable ht = new Hashtable();
            ht.Add("name", cb_list.Text);
            ht.Add("price", tb_price.Text);
            ht.Add("num", tb_num.Text);
            ht.Add("type", cb_type.Text);
            /*Dictionary<string, string> dir = new Dictionary<string, string>();
            dir.Add("name", cb_list.Text);
            Dictionary<string, string> newdir = new Dictionary<string, string>();
            newdir.Add("price", tb_price.Text);
            newdir.Add("num", tb_num.Text);
            if (XmlHelper.self.CheckNodes("db/bill.xml", "data", dir))
            {
                XmlHelper.self.UpdateNode("db/bill.xml", "data", dir, newdir, null);
            }*/
            if (!XmlHelper.self.InsertNode("db/bill.xml", "item",true,"data", ht, null))
            {
                MessageBox.Show("添加失败！");
            }
            bindList();
        }
        private void bindList()
        {
            lb_info.Items.Clear();
            Dictionary<string, BillVo> list = new Dictionary<string, BillVo>();
            XmlNodeList xnl = XmlHelper.self.GetXmlNodeListByXpath("db/bill.xml", "data//item");
            foreach (XmlNode xn in xnl)
            {
                XmlElement xe = (XmlElement)xn;
                string name = xe.GetAttribute("name");
                string type = xe.GetAttribute("type");
                double num = Convert.ToDouble(xe.GetAttribute("num"));
                double price = Convert.ToDouble(xe.GetAttribute("price"));
                if (list.ContainsKey(name))
                {
                    BillVo bv = list[name];
                    if (type == "买入")
                    {
                        bv.num += num;
                        bv.cost += price * num;
                        bv.money = price * bv.num;
                    }
                    else
                    {
                        bv.num -= num;
                        bv.sellMoney += price*num;
                        bv.money = price * bv.num;
                    }
                }else
                {
                    BillVo bv = new BillVo();
                    bv.name = name;
                    bv.num = num;
                    bv.money = num * price;
                    bv.cost = bv.money;
                    list.Add(name, bv);
                }
            }
            double allWin = 0;
            double allCost = 0;
            double allMoney = 0;
            string kg = "          ";
            lb_info.Items.Add("名称         价格      余额      盈亏                均价       本金");
            foreach (KeyValuePair<string, BillVo> de in list)//遍历属性哈希表
            {
                string key = de.Key.Substring(0, de.Key.IndexOf("("));
                double win = Math.Round((de.Value.num * priceList[key] + de.Value.sellMoney - de.Value.cost)*100)*0.01;
                allWin += win;
                allCost += de.Value.cost;
                allMoney += de.Value.num * priceList[key] + de.Value.sellMoney;
                string winbl = (win*100 / de.Value.cost).ToString();
                winbl = winbl.Substring(0, winbl.IndexOf('.') + 3);
                double pjcb= Math.Round((de.Value.cost - de.Value.sellMoney)*10000 / de.Value.num)*0.0001;
                string txt = "";
                txt += de.Key + getSpace(de.Key);
                txt += priceList[key].ToString() + getSpace(priceList[key].ToString());
                txt += de.Value.num.ToString() + getSpace(de.Value.num.ToString());
                txt += win.ToString()+"("+winbl + "%)"+ getSpace(win.ToString()+winbl.ToString()+"   ");
                txt += pjcb.ToString()+ getSpace(pjcb.ToString());
                txt += de.Value.cost.ToString();
                lb_info.Items.Add(txt);
            }
            lb_info.Items.Add("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
            double albl = allWin / allCost;
            string hj= "合计:    本金"+allCost.ToString()+"    当前总资产"+ allMoney .ToString()+ "    盈亏：" + allWin.ToString()+"   "+(Math.Round(albl*100)).ToString() + "%";
            lb_info.Items.Add(hj);
        }
        private string getSpace(string s)
        {
            string kg = "          ";
            return kg.Substring(0, (s.Length>10?20:10) - s.Length);

        }
        private void Form1_Load(object sender, EventArgs e)
        {
            xml = new XmlHelper();
            if (!File.Exists("db/bill.xml"))
            {
                if (!Directory.Exists("db")) Directory.CreateDirectory("db");
                xml.CreateXmlDocument("db/bill.xml", "data");
            }
            webb.ScriptErrorsSuppressed = true;
            webb.Navigate("http://www.btc38.com/httpAPI.php");
            t = new System.Timers.Timer(5000);//实例化Timer类，设置间隔时间为10000毫秒；
            t.Elapsed += new System.Timers.ElapsedEventHandler(readData);//到达时间的时候执行事件；
            t.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
            t.Enabled = true;
            t.Start();
        }
        private void readData(object source, System.Timers.ElapsedEventArgs e)
        {
            this.Invoke(new dltxt(getTxt));
        }
        private void getTxt()
        {
            String str = webb.Document.Body.OuterHtml;
            str = str.Replace("{", "");
            str = str.Replace("}", "");
            str = str.Replace("<BODY>", "");
            str = str.Replace("\r\n", "");
            string[] arr = str.Split(',');
            string res = "";
            foreach(string s in arr)
            {
                if (s.IndexOf("2cny\"") != -1) res += s+",";
            }
            res = res.Replace("2cny", "");
            res = res.Replace("\"", "");
            string[] arr2 = res.Split(',');
            foreach (string pr in arr2)
            {
                string[] tmp = pr.Split(':');
                if (tmp.Length < 2) continue;
                string key = tmp[0].ToUpperInvariant();
                if (priceList.ContainsKey(key))
                {
                    priceList.Remove(key);
                }
                priceList.Add(key, Convert.ToDouble(tmp[1]));
            }
            bindList();
            webb.Navigate("http://www.btc38.com/httpAPI.php");
        }
    }
}
